package data;

import aplication.Rotulador;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Avaliacao;
import model.Questoes;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.xml.sax.SAXException;

/*
 * Pega as questoes do xml e converte objetos pelo framework Digester.
 * Implementa um singletong
 */
public class RepositorioDeQuestoes {

    private Avaliacao avaliacao;
    private static RepositorioDeQuestoes INSTANCE;
    private Questoes questoes;

    /*
     * Faz tudo no construtor :)
     */
    private RepositorioDeQuestoes() {
        avaliacao = new Avaliacao();
        final String rulesfileName = "./src/data/roles.xml";

        Digester d = DigesterLoader.newLoader(new FromXmlRulesModule() {
            @Override
            protected void loadRules() {
                loadXMLRules(new File(rulesfileName));
            }
        }).newDigester();

        try {
            File file = new File("./src/data/questoes.xml");

            questoes = (Questoes) d.parse(file);
            avaliacao.setQuestoes(questoes.getQuestaos());
            Rotulador.getLOGGER().logp(Level.INFO, getClass().getSimpleName(), "RepositorioDeQuestoes", "Digester parse xml to objet concluido!");
        } catch (IOException ex) {
            Rotulador.getLOGGER().logp(Level.SEVERE, getClass().getSimpleName(), "RepositorioDeQuestoes", ex.getMessage());
        } catch (SAXException ex) {
            Rotulador.getLOGGER().logp(Level.SEVERE, getClass().getSimpleName(), "RepositorioDeQuestoes", ex.getMessage());
        }
    }

    public static RepositorioDeQuestoes getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new RepositorioDeQuestoes();
        }
        return INSTANCE;
    }

    public Questoes getQuestoes() {
        return questoes;
    }

    public Avaliacao getAvaliacao() {
        return avaliacao;
    }

    public void setAvaliacao(Avaliacao avaliacao) {
        this.avaliacao = avaliacao;
    }
}
